﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.AccessControl;
using System.Text;
using Serie_Counter.General;

namespace Serie_Counter.DataLayer
{
    public class IO_Settings : Settings
    {
        private static Settings settings = null;
        private const string SETTINGSPATH = "settings.dat";

        public IO_Settings():base()
        {
            
        }

        public static Settings GetSettings()
        {
            if (settings == null)
            {
                ReadSettings();
            }
            return settings;
        }

        public static void SetSettings(Settings settingsPara)
        {
            settings = settingsPara;
        }

        private static void ReadSettings()
        {
            try
            {
                if(File.Exists(SETTINGSPATH))
                {
                    using (FileStream read = new FileStream(SETTINGSPATH,FileMode.Open,FileAccess.Read))
                    {
                        BinaryFormatter formatter = new BinaryFormatter();
                        read.Position = 0;
                        settings = (Settings)formatter.Deserialize(read);
                    }
                }
                else
                {
                    writeSettings();
                }
            }
            catch (Exception e)
            {
                
                Debug.WriteLine(e.Message);
            }
        }

        public static void writeSettings()
        {
            if (settings == null)
            {
                settings = new Settings();
            }

            try
            {
                using(FileStream write = new FileStream(SETTINGSPATH,FileMode.Create,FileAccess.Write))
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(write,settings.Serialize());
                }
            }
            catch (Exception e)
            {
                
                Debug.WriteLine(e.Message);
            }
        }
    }
}
